package com.xb.p23_asynctask;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    final String TAG="asynctask main";

    Button button;

    ProgressBar progressBar;

    TextView textView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button=findViewById(R.id.btn_async);
        button.setOnClickListener(this);

        progressBar=findViewById(R.id.progressbar);
        textView=findViewById(R.id.tv_async);
    }

    @Override
    public void onClick(View v) {
        TimeTickLoad timeTickLoad=new TimeTickLoad();
        timeTickLoad.execute(1000);
    }

    public class TimeTickLoad extends AsyncTask<Integer,Integer,String>{

        @Override
        protected void onPreExecute() {
            Log.i(TAG,"onPreExecute...");
            textView.setText("onPreExecute...");
            progressBar.setVisibility(ProgressBar.VISIBLE);
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            Log.i(TAG,"onPostExecute...");
            //进度条执行结束
            textView.setText("onPostExecute..."+s);
            super.onPostExecute(s);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            Log.i(TAG,"onProgressUpdate...");
            //进度更新
            progressBar.setProgress(values[0]);
            textView.setText("onProgressUpdate...");
            super.onProgressUpdate(values);
        }

        @Override
        protected String doInBackground(Integer... integers){
            Log.i(TAG,"doInBackground...");

            //耗时的大任务再次处理，不能进行UI更新的操作
            for(int i=0;i<=10;i++){
                publishProgress(i*10);
                try {//取出传递过来的参数
                    Thread.sleep(integers[0]);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "执行完毕";
        }
    }
}